//
//  InstallViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/5/6.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//
#import "InstallViewController.h"
#import "RootViewController.h"
#import "InstallCell.h"
#import "InstallCell1.h"
#import "Common.h"
#import "LoginViewController.h"//登录页面
#import "ManagersViewController.h"//账户管理
#import "TopBackView.h"
#import "CarTypeViewController.h"//常用车型
#import "DepartViewController.h"//常用发车 送达地址
#import "InvoiceViewController.h"//发票中心
#import "MessageViewController.h"//消息
#import "CallCenterViewController.h"//客服
#import "MineOrderVC.h"
#import "QiniuSDK.h"
#import <UIImageView+WebCache.h>
#import "HistoryCarStyleVC.h"
#import "WKProgressHUD.h"
#import "RLNetworkHelper.h"

#import "EvaluateViewController.h"
#import "MyScoreViewController.h"
#import "OrderDetailVC1.h"
#import "DriverScoreVC.h"

@interface InstallViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableDictionary *dataDictionary;
@property (nonatomic,strong) NSMutableDictionary *orderDictionary;
@property (nonatomic,copy) NSString *token;
@property (nonatomic,copy) NSString *domain;
@property (nonatomic,strong) UIImageView *imageV;
@property (nonatomic,strong) NSMutableArray *imagesArray;
@property (nonatomic,strong) UIView *netView;

@end

@implementation InstallViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray = [NSMutableArray array];
    self.imagesArray = [NSMutableArray array];
    self.dataDictionary = [NSMutableDictionary dictionary];
    self.orderDictionary = [NSMutableDictionary dictionary];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;

    
    Common *c = [[Common alloc]init];
    self.netView = [c noInternet:@"网络异常，请检查网络配置" and:self action:@selector(NoNetpressBtn) andCGreck:CGRectMake(0, 0, screenWidth, screenHeight - 64 - 49)];
    
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"商户中心"];
    
//    self.imagesArray = [NSMutableArray arrayWithObjects:@"personal_orders",@"personal_start",@"personal_end",@"personal_car",@"personal_invoice",@"notification-bell",@"personal_kefu", nil];
    
//    self.imagesArray = [NSMutableArray arrayWithObjects:@"personal_orders",@"personal_score",@"personal_start",@"personal_end",@"personal_car",@"personal_about", nil];
//
    
//     self.imagesArray = [NSMutableArray arrayWithObjects:@"personal_orders",@"personal_start",@"personal_end",@"personal_car",@"123", nil];
    
    
    topBackView.leftButton.hidden = YES;
    topBackView.rightButton.hidden = YES;
 
    [self.view addSubview:topBackView];
    
     self.view.backgroundColor = WhiteColor;
//
 
    [self initSubViews];

//    [self initDataSource];
    
//    [self createNetWorkAndStatus];
    [self judgeNetWork];
    
}

-(void)createNetWorkAndStatus
{
  
    [self.view addSubview:self.netView];
    
}

-(void)NoNetpressBtn
{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        [self.netView removeFromSuperview];
        [self initDataSource];
    }

}

-(void)judgeNetWork
{
    if (![RLNetworkHelper isConnectedToNetwork]) {
        [self.tableView addSubview:self.netView];
    } else {
        
        [self.netView removeFromSuperview];
        [self initDataSource];
    }
}

-(void)initDataSource
{
    //用户信息接口
    
    [Common requestWithUrlString:user_info contentType:application_json finished:^(id responseObj) {
               
        if ([responseObj[@"success"] boolValue]) {
            
        self.dataDictionary = [NSMutableDictionary dictionaryWithDictionary:responseObj[@"data"]];
            
                        //赋值
        [self getValueString];
        } else {
            
//        [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];


        }
        
    } failed:^(NSString *errorMsg) {
        
        NSLog(@"%@",errorMsg);
    }];
    

    

//    isBaseUser
//    self.dataArray = [NSMutableArray arrayWithObjects:@"我的订单",@"我的积分",@"常用发车地址管理",@"常用送达地址管理",@"常用车型管理",@"关于慧运车", nil];

}

#pragma mark 赋值方法

-(void)getValueString
{
    if ([self.dataDictionary[@"pic"] isEqual:[NSNull null]]) {
        self.imageV.image = [UIImage imageNamed:@"personal_picture"];
    } else {
    
    //拼接图片url
    NSString *urlString = [NSString stringWithFormat:@"%@",self.dataDictionary[@"pic"]];
        
        [self.imageV sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"personal_picture"]];
        
    }
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    InstallCell *cell = [self.tableView cellForRowAtIndexPath:index];
    cell.nameLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"phone"]];
    cell.scoreL.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"levelName"]];
    
}


-(void)initSubViews
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = GrayColor;
    [self.view addSubview:self.tableView];
    
}


#pragma mark UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else {
        
        return   self.dataArray.count;

    }
    
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    
    if (indexPath.section == 0) {
        
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        
        NSString *valueString = [userDefaults objectForKey:@"login"];
        if (valueString == nil) {
            //未登录
            
            NSString *string = @"installFirstCell1";
            InstallCell1 *cell = [tableView dequeueReusableCellWithIdentifier:string];
            if (!cell) {
                cell = [[InstallCell1 alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:string];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
//            [cell.pictureButton addTarget:self action:@selector(buttonToGetPicture) forControlEvents:UIControlEventTouchUpInside];
            
            self.imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50 * kWidth, 50 * kHeight)];
            self.imageV.layer.cornerRadius = 25 * kWidth;
            self.imageV.layer.masksToBounds = YES;
            self.imageV.image = [UIImage imageNamed:@"personal_picture"];
            [cell.pictureButton addSubview:self.imageV];
            
            [cell.loginButton addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
            cell.pictureButton.userInteractionEnabled = NO;
            
            return cell;

        } else {
            //已登录
            NSString *string = @"installFirstCell";
            InstallCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
            if (!cell) {
                cell = [[InstallCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:string];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
//            [cell.pictureButton addTarget:self action:@selector(buttonToGetPicture) forControlEvents:UIControlEventTouchUpInside];
            
            self.imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50 * kWidth, 50 * kHeight)];
            self.imageV.layer.cornerRadius = 25 * kWidth;
            self.imageV.layer.masksToBounds = YES;
            self.imageV.image = [UIImage imageNamed:@"personal_picture"];
            [cell.pictureButton addSubview:self.imageV];
            
            return cell;

        }
        
      
    } else {

    NSString *string = @"installCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    
        cell.textLabel.text = self.dataArray[indexPath.row];
        cell.textLabel.font = Font(13);
        cell.textLabel.textColor = littleBlackColor;
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
    
        cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"personal_arrow"]];
        
        cell.imageView.image = [UIImage imageNamed:self.imagesArray[indexPath.row]];
    return cell;
        
    }
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        
        return (indexPath.section == 0) ? 78 * kHeight : cellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *string = [userDefaults objectForKey:@"login"];
    
    
    if (string == nil ) {
        
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        
        [self presentViewController:loginNC animated:YES completion:nil];
        
    } else {
        
        
        if (indexPath.section == 0) {
            //账户管理
            
            ManagersViewController *managerVC = [[ManagersViewController alloc]init];
//            [Common isLogin:self andPush:managerVC];
            [self.navigationController pushViewController:managerVC animated:YES];
            
        } else {
            
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            
            NSString * isBaseUser = [userDefaults objectForKey:@"isBaseUser"];

            isBaseUser = @"no";
            
            if ([isBaseUser isEqualToString:@"yes"]) {
                
                if (indexPath.row == 0) {
                    
                    MineOrderVC *mineVC = [[MineOrderVC alloc]init];
                    mineVC.hide = @"1";
                    //                [Common isLogin:self andPush:mineVC];
                    [self.navigationController pushViewController:mineVC animated:YES];
                    
                }
                
                if (indexPath.row == 2) {
                    
                    DepartViewController *departVC = [[DepartViewController alloc]init];
                    departVC.topTitle = @"0";
                    departVC.cancelBtn = @"1";
                    //                [Common isLogin:self andPush:departVC];
                    [self.navigationController pushViewController:departVC animated:YES];
                }
                if (indexPath.row == 1) {
                    
                    //                OrderDetailVC1 *order = [[OrderDetailVC1 alloc]init];
                    //                order.number = 3;
                    //                [self.navigationController pushViewController:order animated:YES];
                    
                    //                评价
                    EvaluateViewController *evalu = [[EvaluateViewController alloc]init];
                    [self.navigationController pushViewController:evalu animated:YES];
                    
                    //                //积分
                    MyScoreViewController *scoreVC = [[MyScoreViewController alloc]init];
                    [self.navigationController pushViewController:scoreVC animated:YES];
                    
                    //                DriverScoreVC *drive = [[DriverScoreVC alloc]init];
                    //                [self.navigationController pushViewController:drive animated:YES];
                    
                }
                
                if (indexPath.row == 3) {
                    //常用送达地址
                    DepartViewController *departVC = [[DepartViewController alloc]init];
                    departVC.topTitle = @"1";
                    departVC.cancelBtn = @"1";
                    //                [Common isLogin:self andPush:departVC];
                    [self.navigationController pushViewController:departVC animated:YES];
                    
                }
                
                if (indexPath.row == 4) {
                    
                    //常用车型
                    CarTypeViewController *carVC = [[CarTypeViewController alloc]init];
                    
                    //                [Common isLogin:self andPush:carVC];
                    [self.navigationController pushViewController:carVC animated:YES];
                    
                }
            }else{
                
                if (indexPath.row == 0) {
                    
                    MineOrderVC *mineVC = [[MineOrderVC alloc]init];
                    mineVC.hide = @"1";
                    //                [Common isLogin:self andPush:mineVC];
                    [self.navigationController pushViewController:mineVC animated:YES];
                    
                }
                
                if (indexPath.row == 1) {
                    
                    DepartViewController *departVC = [[DepartViewController alloc]init];
                    departVC.topTitle = @"0";
                    departVC.cancelBtn = @"1";
                    //                [Common isLogin:self andPush:departVC];
                    [self.navigationController pushViewController:departVC animated:YES];
                }

                
                if (indexPath.row == 2) {
                    //常用送达地址
                    DepartViewController *departVC = [[DepartViewController alloc]init];
                    departVC.topTitle = @"1";
                    departVC.cancelBtn = @"1";
                    //                [Common isLogin:self andPush:departVC];
                    [self.navigationController pushViewController:departVC animated:YES];
                    
                }
                
                if (indexPath.row == 3) {
                    
                    //常用车型
                    CarTypeViewController *carVC = [[CarTypeViewController alloc]init];
                    
                    //                [Common isLogin:self andPush:carVC];
                    [self.navigationController pushViewController:carVC animated:YES];
                    
                }

                
            }
            
            }
            
            
    
//            if (indexPath.row == 4) {
//                /**
//                 索取发票
//                 
//                 */
//                
//                InvoiceViewController *invoiceVC = [[InvoiceViewController alloc]init];
//                [self.navigationController pushViewController:invoiceVC animated:YES];
//            }
//            
//            
//            if (indexPath.row == 5) {
//                /**
//                 消息
//                 */
//                
//                MessageViewController *message = [[MessageViewController alloc]init];
//                [self.navigationController pushViewController:message animated:YES];
//            }
            
//            if (indexPath.row == 5) {
//                /**
//                 客服中心
//                 
//                 */
//                //关于慧运车
//                CallCenterViewController *callVC = [[CallCenterViewController alloc]init];
//                [self.navigationController pushViewController:callVC animated:YES];
//                
//                }
        
        }
    
}


#pragma mark 获取图片
-(void)buttonToGetPicture
{
    
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf getPictureFromCamera];
        
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf getPictureFromLibrary];

    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];


    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark 拍照
-(void)getPictureFromCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];

}

#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
       
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        
        self.imageV.image = image;

        //上传服务器
        [self getTokenFromQN];
        
    }];
}


-(NSData *)getImageWith:(UIImage *)image
{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 0.5);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark 从七牛获取Token
-(void)getTokenFromQN
{
//    NSString *string = [NSString stringWithFormat:@"%@qiniu/upload/ticket",Main_interface];
    
    [Common requestWithUrlString:qiniu_token contentType:application_json finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            

            self.token = responseObj[@"data"];
        [self uploadImageToQNWithData:[self getImageWith:self.imageV.image]];
        }
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
    

}



-(void)uploadImageToQNWithData:(NSData *)data
{
    
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        NSLog(@"%@",resp);
        
        [self changePhotoWithString:resp[@"key"]];
        
        
    } option:uploadOption];
}

//调用更换头像接口
-(void)changePhotoWithString:(NSString *)string
{
    
//    NSString *urlString = [NSString stringWithFormat:@"%@user/modify",Main_interface];
    
    NSDictionary *dictionary =
                @{@"pic":string,
                  @"pwd":@"",
                  @"name":@"",
                  @"email":@"",
                  @"gender":@"",
                  @"birthday":@"",
                  @"orgimage":@"",
                  };
    
    
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:user_modify parms:dictionary finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
        
        
        [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];

        
    } failedBlock:^(NSString *errorMsg) {
        
        NSLog(@"%@",errorMsg);
        
    }];
}

-(void)next
{
    ManagersViewController *managerVC = [[ManagersViewController alloc]init];
    [Common isLogin:self andPush:managerVC];

}

-(void)viewWillAppear:(BOOL)animated{
    
    NSUserDefaults *userDefaults1 = [NSUserDefaults standardUserDefaults];
    
    NSString * isBaseUser = [userDefaults1 objectForKey:@"isBaseUser"];
    isBaseUser = @"no";
    if ([isBaseUser isEqualToString:@"yes"]) {
        self.dataArray = [NSMutableArray arrayWithObjects:@"我的订单",@"商户积分",@"常用发车地址管理",@"常用送达地址管理",@"常用车型管理", nil];
        self.imagesArray = [NSMutableArray arrayWithObjects:@"personal_orders",@"personal_score",@"personal_start",@"personal_end",@"personal_car", nil];
        
    }else{
        self.dataArray = [NSMutableArray arrayWithObjects:@"我的订单",@"常用发车地址管理",@"常用送达地址管理",@"常用车型管理", nil];
        self.imagesArray = [NSMutableArray arrayWithObjects:@"personal_orders",@"personal_start",@"personal_end",@"personal_car", nil];
    }
    
    [self.tableView reloadData];
    
    
    
    
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:NO];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"dismiss" object:nil];
    
    
//    [[NSNotificationCenter defaultCenter]postNotificationName:kReachabilityChangedNotification object:nil userInfo:nil];

    //修改信息后 重新请求数据
    
//    [self initDataSource];
//    [self.tableView reloadData];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *valueString = [userDefaults objectForKey:@"login"];
//    if (valueString == nil) {

//    NSIndexSet *index = [[NSIndexSet alloc]initWithIndex:0];
    
//    [self.tableView reloadSections:index withRowAnimation:UITableViewRowAnimationNone];
//    }
    
    [self createNetWorkAndStatus];
    [self judgeNetWork];

//    [self initDataSource];

    
}

-(void)viewDidAppear:(BOOL)animated
{
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
